<?php

namespace app\index\controller;

use app\common\controller\IndexController;
use app\index\model\CardsTrans;
use app\index\model\Cards as cardsModel;
use app\index\model\CardsLog;
use app\common\model\Cards as ComCardsModel;
use app\common\model\CardsTrans as ComCardsTrans;
use think\App;
use think\facade\Db;
use think\facade\View;
use think\facade\Cache;

require_once('tcpdf/tcpdf.php');

/**
 * 卡管理
 * Class ArticleType
 * @package app\manage\controller
 */
class Cards extends IndexController
{
    public $child_menu_class;

    public function __construct(App $app)
    {
        parent::__construct($app);
        $mobile = Db::name('user')->where(['id' => $this->user_id])->value('mobile');
        View::assign([
            'menu_class' => 'cards',
            'card_state' => ['AL', 'AK', 'AZ', 'AR', 'CO', 'CA', 'CT', 'DE', 'DC', 'FL', 'GA', 'HI', 'ID', 'IL', 'IN', 'IA',
                'KS', 'KY', 'LA', 'ME', 'MA', 'MD', 'MI', 'MN', 'MS', 'MO', 'MT', 'NE', 'NV', 'NH', 'NJ', 'NM', 'NY', 'NC', 'ND', 'OH',
                'OK', 'OR', 'PA', 'RI', 'SC', 'SD', 'TN', 'TX', 'UT', 'VT', 'VA', 'WA', 'WV', 'WI', 'WY'],
            'mobile' => $mobile
        ]);
    }

    /**
     * 余额列表
     * @author 救火队队长
     */
    public function index()
    {
        if ($this->request->isPost()) {
            $return = $this->cardAdd();
            $blog = $return['blog'];
            $msg = $return['msg'];
            if ($blog) {
                return $this->scs($msg);
            } else {
                return $this->err($msg);
            }
        }

        $users_list = Db::name('user')->where(['id' => $this->user_id])->find();
        $create_amount = $users_list['create_amount'];
        $user_balance  = $users_list['balance'];
        $grade         =   $users_list['grade'];
        if($grade == 0){
            return $this->redirect(url('/index/user/cardCheck'));
        }

        $cardSetList = $this->getCardSet(false);
        $address_list = Db::name('card_default_address')->where(['user_id' => $this->user_id])->find();
        $list_new    = [];
        foreach ($cardSetList as $k=>$v){
            $list_new[$v['bank_type']][$v['card_type']]['rate_fund'] = $v['rate_fund'];
            $list_new[$v['bank_type']][$v['card_type']]['open_amount'] = $v['open_amount'];
        }

//        $age = array_column($cardSetList, 'is_refe');
//        array_multisort($age, SORT_DESC, $cardSetList);
        $card_type_first = 556305;
//        if($cardSetList){
//            $age = array_column($cardSetList, 'bank_type');
//            array_multisort($age, SORT_ASC, $cardSetList);
//            foreach ($cardSetList as $k_first=>$v_first){
//                $is_used = $v_first['is_used'];
//                if($is_used != 1){
//                    $card_type_first = $v_first['card_type'];
//                    break;
//                }
//            }
//        }
        $card_type   = input('get.c' , $card_type_first);
        $user_set_list = Db::name('user_set')->where(['id'=>1])->find();
        $card_set_list = json_decode($user_set_list['card_set'] ,true);
        $array_bank_type = [];

        foreach ($card_set_list as $k_set => $v_set){
            $array_bank_type[$v_set['card_type']] = $v_set['bank_type'];
        }
        if(!isset($array_bank_type[$card_type])){
            $card_type = $card_type_first;
        }
        $bank_type   = $array_bank_type[$card_type];
        if(!isset($list_new[$bank_type][$card_type])){
            $card_type = $card_type_first;
            $bank_type = $array_bank_type[$card_type];
        }

        $cards_p616 = [556766,558068,531847,556735];
        $cards_w990 = [556305,527811];
        $cards_bank1= [556766,558068,531847,556735,556305,527811];
        $is_open_p616 = getSetting('is_open_p616');
        $is_open_w990 = getSetting('is_open_w990');
        $is_open_bank3 = getSetting('is_open_bank3');
        //new_card array
        $new_card_array = [];

        View::assign([
            'menu_child' => 'cards',//556305
            'address_list' => $address_list,
            'card_array' => $cardSetList,//556305
            'open_amount' => $list_new[$bank_type][$card_type]['open_amount'],
            'server_amount' => $list_new[$bank_type][$card_type]['rate_fund'],
            'create_amount' => round($create_amount, 0),
            'user_balance' => $user_balance,
            'default_card' => $card_type,
            'bank_type'    => $bank_type,
            'is_open_p616' => $is_open_p616,
            'is_open_w990' => $is_open_w990,
            'is_open_bank3'=> $is_open_bank3,
            'cards_p616'    => $cards_p616,
            'cards_w990'    => $cards_w990,
            'cards_bank1'  => $cards_bank1
        ]);
        View::layout(true);
        return View::fetch();
    }


    public function changeAddress()
    {
        $data = input('param.');
        if (empty($data['default_address'])) return $this->err('默认街道地址不能为空.');
        if (empty($data['default_city'])) return $this->err('默认城市不能为空.');
        if (empty($data['default_state'])) return $this->err('默认州不能为空.');
        if (empty($data['default_zip'])) return $this->err('默认邮编不能为空.');

        if (check_param($data['default_address'] , 'zn')) return $this->err('默认街道地址不能有中文字符.');
        if (check_param($data['default_city'] , 'zn')) return $this->err('默认城市不能有中文字符.');
        if (check_param($data['default_state'] , 'zn')) return $this->err('默认州不能有中文字符.');
        if (check_param($data['default_zip'] , 'zn')) return $this->err('默认邮编不能有中文字符.');
        if (!is_numeric($data['default_zip'])) return $this->err('默认邮编必须为数字.');

        $user_id = $this->user_id;
        $list = Db::name('card_default_address')->where(['user_id' => $user_id])->find();
        if (empty($list)) {
            $re = Db::name('card_default_address')->save([
                'user_id' => $user_id,
                'address' => $data['default_address'],
                'city' => $data['default_city'],
                'state' => $data['default_state'],
                'zip' => $data['default_zip'],
                'ctime' => getUtcTime()
            ]);
        } else {
            $re = Db::name('card_default_address')->where(['user_id' => $user_id])
                ->update([
                    'address' => $data['default_address'],
                    'city' => $data['default_city'],
                    'state' => $data['default_state'],
                    'zip' => $data['default_zip']
                ]);
        }
        if ($re) {
            return $this->scs('更新默认地址成功.');
        } else {
            return $this->err('更新默认地址失败.');
        }
    }

    public function cardAdd()
    {
        $data = input('param.');
        $card_type   = $data['card_type'];
        $bank_type   = $data['bank_type'];

        if($bank_type == 3){
            $is_action_bank3 = getSetting('is_action_bank3');
            if($is_action_bank3 == 1){
                return ['blog' => false, 'msg' => '卡头正在维护中,请稍后操作.'];
            }
        }

        $cards_p616 = [556766,558068,531847,556735];
        $cards_w990 = [556305,527811];
        $cards_bank1 = [556305,527811,556766,558068,531847,556735];
        $is_open_p616 = getSetting('is_open_p616');
        $is_open_w990 = getSetting('is_open_w990');
        if(in_array($card_type , $cards_p616)){
            if($is_open_p616 != 1){
                return ['blog' => false, 'msg' => '卡头正在维护,请选择其他卡头'];
            }
        }
        if(in_array($card_type , $cards_w990)){
            if($is_open_w990 != 1){
                return ['blog' => false, 'msg' => '卡头正在维护,请选择其他卡头'];
            }
        }
        $is_open_bank3 = getSetting('is_open_bank3');
        if(!in_array($card_type , $cards_bank1)){
            if($bank_type == 3){
                if($is_open_bank3 != 1){
                    return ['blog' => false, 'msg' => '卡头正在维护,请选择其他卡头'];
                }
            }

        }
        //获取用户信息
        $user_list = Db::name('user')->find($this->user_id);
        $current_balance = $user_list['balance'];
        $user_name = $user_list['username'];
        $create_amount = $user_list['create_amount'];
        $status    = $user_list['status'];
        if($status == 2){
            return ['blog' => false, 'msg' => '账号已冻结,请联系管理员'];
        }

        $cardSetList = $this->getCardSet();
        if(isset($cardSetList[$bank_type][$card_type])){
            if($cardSetList[$bank_type][$card_type]['is_used'] == 1){
                return ['blog' => false, 'msg' => '您要创建的卡头不匹配,请重新选择.'];
            }
        }else{
            return ['blog' => false, 'msg' => '您要创建的卡头不匹配,请重新选择..'];
        }
        $card_max       = $cardSetList['max_card']; //建卡上限
        $open_amount    = $cardSetList[$bank_type][$card_type]['open_amount'];
        $server_amount  = $cardSetList[$bank_type][$card_type]['rate_fund'];

        //$user_type=1 spend_limit=消费限额 | =0 spend_limit=充值金额
        $spend_limit = trim($data['spend_limit']);
        //card_num 建卡的数量 不超过20
        $card_num = $data['card_num'];

        $first_name     = trim($data['first_name']);
        $last_name      = trim($data['last_name']);
        $middle_name    = trim($data['middle_name']);

        $first_name = str_replace(' ', 'and', $first_name);
        if (!check_param($first_name, 'en')) {
            return ['blog' => false, 'msg' => 'FirstName必须为英文.'];
        }
        if (strlen($first_name) > 20) {
            return ['blog' => false, 'msg' => 'FirstName不能大于20个字符'];
        }
        $last_name = str_replace(' ', 'and', $last_name);
        if (!check_param($last_name, 'en')) {
            return ['blog' => false, 'msg' => 'FirstName必须为英文.'];
        }
        if (strlen($last_name) > 20) {
            return ['blog' => false, 'msg' => 'LastName不能大于20个字符.'];
        }
        if (strlen($data['state']) > 2) {
            return ['blog' => false, 'msg' => "'州'不能大于2个字符."];
        }
        if (strlen($data['billing_address']) > 30) {
            return ['blog' => false, 'msg' => "'街道地址'不能大于30个字符."];
        }
        if (strlen($data['city']) > 20) {
            return ['blog' => false, 'msg' => "'城市'不能大于20个字符."];
        }
        if(!empty($middle_name)){
            $middle_name = str_replace(' ', 'and', $middle_name);
            if (!check_param($middle_name, 'en')) {
                return ['blog' => false, 'msg' => 'MiddleName必须为英文.'];
            }
            if (strlen($middle_name) > 20) {
                return ['blog' => false, 'msg' => 'MiddleName不能大于20个字符.'];
            }
        }
        if (check_param($data['billing_address'] , 'zn')) {
            return ['blog' => false, 'msg' => '街道地址不能有中文字符.'];
        }
        if (check_param($data['city'] , 'zn')) {
            return ['blog' => false, 'msg' => '城市不能有中文字符.'];
        }
        if (check_param($data['state'] , 'zn')) {
            return ['blog' => false, 'msg' => '州不能有中文字符.'];
        }
        if (check_param($data['zip'] , 'zn')) {
            return ['blog' => false, 'msg' => '邮编不能有中文字符.'];
        }
        if (!is_numeric($data['zip'])) {
            return ['blog' => false, 'msg' => '邮编必须为数字.'];
        }

        //判断建卡数量是否是负数
        if ($card_num < 1) {
            return ['blog' => false, 'msg' => '开卡数量不能为负数.'];
        }
        //判断是否超过会员每次建卡上限
        if ($card_num > 20) {
            return ['blog' => false, 'msg' => '每次建卡不能超过20张.'];
        }


        $redis_key_name = 'user_card_add_' . $user_name;
        //判断改用户是否多开页面重复建卡
        $create_card_course = Cache::store('redis')->get($redis_key_name);
        //如果是，返回错误，不允许多开窗口建卡
        if ($create_card_course) {
            return ['blog' => false, 'msg' => '正在建卡中，请稍后再试.'];
        } else {

            if (!check_param($spend_limit, 'zInt')) {
                return ['blog' => false, 'msg' => '充值金额请填写整数.'];
            }
            //充值金额小于开卡金额，提示错误
            if (($spend_limit - $create_amount) < 0) {
                return ['blog' => false, 'msg' => "充值金额必须大于 $ {$create_amount}."];
            }

            $total_amount = ($open_amount + $spend_limit + $spend_limit * $server_amount) * $card_num;
            $total_amount = getSprintf($total_amount);
            //判断用户余额是否充足
            if (($total_amount - $current_balance) > 0) {
                return ['blog' => false, 'msg' => "账户余额不足."];
            }
            //判断改用户已建卡数量 和 将要建卡的数量 是否大于最大建卡数
            $card_count = Db::name('cards')->where(['user_id' => $this->user_id])->count();

            if (($card_count + $card_num) > $card_max) {
                return ['blog' => false, 'msg' => "已超过用户最大建卡数量."];
            }
            //建卡
            $cdModel = new cardsModel();
            $re = $cdModel->cardsAdd($data, $user_list, $card_type, $cardSetList , $bank_type);
            //建卡完成后删除重复建卡的标识
            Cache::store('redis')->delete($redis_key_name);
            if ($re) {
                return ['blog' => true, 'msg' => "创建卡({$re})张成功."];
            } else {
                return ['blog' => false, 'msg' => ($bank_type == 3) ? "渠道维护,请尝试创建527811,531847,556305." : "建卡失败."];
            }
        }

    }

    public function cardList()
    {
        $card_count = Db::name('cards')->where(['user_id'=>$this->user_id])->count();
        if($card_count <= 0){
            return $this->redirect(url('/index/cards/index'));
        }
        $users_list = Db::name('user')->where(['id' => $this->user_id])->find();
        $grade         =   $users_list['grade'];
        if($grade == 0){
            return $this->redirect(url('/index/user/cardCheck'));
        }

        if ($this->request->isPost()) {
            $data = input('param.');
            $cdModel = new cardsModel();
            return $cdModel->tableData($data + ['user_id' => $this->user_id]);
        }
        View::assign([
            'menu_child' => 'list_card',
        ]);
        return View::fetch();
    }

    public function getCardDetail($card_id, $type)
    {
        $card_list = Db::name('cards')->find($card_id);
        $memo       = $card_list['memo'];
        $bank_type  = $card_list['bank_type'];
        $card_type  = $card_list['card_type'];
        $card_status= $card_list['status'];
        $user_id    = $card_list['user_id'];
        $check_status = $card_list['check_status'];

        if($type == 'info' || $type == 'info_del'){
            ComCardsModel::checkCardBalanceApi($card_id);
        }

        $user_list      = Db::name('user')->where(['id'=>$user_id])->find();
        $user_balance   = $user_list['balance'];
        $is_code        = $user_list['is_code']; // 是否开启消费记录包含code信息  0否|1是

        $card_detail = Db::name('cards_detail')->where(['memo' => $memo])->find();
        $address = $card_detail['billing_address'] . ', ' .
            $card_detail['city'] . ', ' .
            $card_detail['state'] . ' ' .
            $card_detail['zip'];
        //卡状态 不等于 开卡中 查询银行卡余额更新本地金额
        $exp_date = $card_list['exp_date'];
        if($bank_type == 3){
            $exp_date = substr($exp_date, 0, 2) . '/' . substr($exp_date, 2, 2);
            $cvv      = $card_list['cvv'];
        }else{
            $cvv      = empty($card_list['cvv']) ? '开卡中' : $card_list['cvv'];
            $exp_date = empty($exp_date) ? '开卡中' : substr($exp_date, 5, 2) . '/' . substr($exp_date, 2, 2);
        }

        $card_num = $card_list['card_num'] ?? '';
        //已删除的卡 只显示卡前6位和后4位，并且cvv和过期时间 隐藏
        if($card_status == 3){
            if(!empty($card_num)){
                $card_num = substr($card_num , 0 , 6) . " ****** " . substr($card_num , -4);
            }
            $cvv        = "***";
            $exp_date   = "***";
        }

        View::assign([
            'menu_child' => 'list_card',
            'card_num' => $card_num,
            'balance' => $card_list['balance'] ?? '',
            'balance_account' => $card_list['balance_account'],
            'cvv' => $cvv,
            'exp_date' => $exp_date,
            'address' => $address,
            'billing_address' => $card_detail['billing_address'] ?? '',
            'city' => $card_detail['city'] ?? '',
            'state' => $card_detail['state'] ?? '',
            'zip' => $card_detail['zip'] ?? '',
            'card_id' => $card_id,
            'remark' => $card_list['remarks'],
            'type' => $type,
            'card_status' => $card_status,
            'user_balance'=> $user_balance,
            'is_code' => $is_code,
            'check_status' => $check_status
        ]);
        if ($type == 'info') {
            $cardSetList = $this->getCardSet();
            View::assign([
                'server_amount' => $cardSetList[$bank_type][$card_type]['rate_fund']
            ]);
        }
    }

    public function cardInfo()
    {
        $card_id = input('get.card_id');
        if (!$this->check_cardId_user($card_id)) return $this->err('用户和卡的详细信息不匹配');
        $this->getCardDetail($card_id, 'info');
        return View::fetch();
    }

    public function cardInfoAddress()
    {
        $card_id = input('get.card_id');
        if (!$this->check_cardId_user($card_id)) return $this->err('用户和卡的详细信息不匹配');
        $this->getCardDetail($card_id, 'info_address');
        return View::fetch();
    }

    public function cardInfoDet()
    {
        $card_id = input('get.card_id');
        if (!$this->check_cardId_user($card_id)) return $this->err('用户和卡的详细信息不匹配');
        $this->getCardDetail($card_id, 'info_det');
        return View::fetch();
    }

    public function cardInfoDel()
    {
        $card_id = input('get.card_id');
        if (!$this->check_cardId_user($card_id)) return $this->err('用户和卡的详细信息不匹配');
        $this->getCardDetail($card_id, 'info_del');
        return View::fetch();
    }

    public function cardInfoRemark()
    {
        $card_id = input('get.card_id');
        if (!$this->check_cardId_user($card_id)) return $this->err('用户和卡的详细信息不匹配');
        $this->getCardDetail($card_id, 'info_remark');
        return View::fetch();
    }

    public function cardInfoTran()
    {
        if ($this->request->isPost()) {
            $data = input('param.');
            if (empty($data['card_id'])) return $this->err('此卡不存在');
            if (!$this->check_cardId_user($data['card_id'])) return $this->err('用户和卡的详细信息不匹配');
            $cdLogModel = new CardsTrans();
            return $cdLogModel->tableDataInfo($data + ['user_id' => $this->user_id]);
        }
        $card_id = input('get.card_id');
        if (!$this->check_cardId_user($card_id)) return $this->err('用户和卡的详细信息不匹配');
        $this->getCardDetail($card_id, 'info_tran');
        return View::fetch();
    }

    public function cardInfoTranCode()
    {
        if ($this->request->isPost()) {
            $data = input('param.');
            if (empty($data['card_id'])) return $this->err('此卡不存在');
            if (!$this->check_cardId_user($data['card_id'])) return $this->err('用户和卡的详细信息不匹配');
            $cdLogModel = new CardsTrans();
            return $cdLogModel->tableDataInfoCode($data + ['user_id' => $this->user_id]);
        }
        $card_id = input('get.card_id');
        if (!$this->check_cardId_user($card_id)) return $this->err('用户和卡的详细信息不匹配');
        $this->getCardDetail($card_id, 'info_tran_code');
        return View::fetch();
    }

    public function cardInfoLog()
    {
        if ($this->request->isPost()) {
            $data = input('param.');
            if (empty($data['card_id'])) return $this->err('此卡不存在');
            if (!$this->check_cardId_user($data['card_id'])) return $this->err('用户和卡的详细信息不匹配');
            $cdLogModel = new CardsLog();
            return $cdLogModel->tableData($data);
        }
        $card_id = input('get.card_id');
        if (!$this->check_cardId_user($card_id)) return $this->err('用户和卡的详细信息不匹配');
        $this->getCardDetail($card_id, 'info_log');
        return View::fetch();
    }


    public function cardAction()
    {
        $data = input('param.');
        $card_id = $data['card_id'];
        $type = $data['type'];
        $amount = $data['amount'] ?? 0.00;
        if (!$this->check_cardId_user($card_id)) return $this->err('用户和卡的详细信息不匹配');
        $re = false;
        $user_list = Db::name('user')->find($this->user_id);
        $user_balance = $user_list['balance'];
        $user_name = $user_list['username'];
        $create_amount = $user_list['create_amount'];
        $status    = $user_list['status'];
        if($status == 2){
            return $this->err('账号已冻结,请联系管理员');
        }

        $card_list = Db::name('cards')->where(['user_id' => $this->user_id, 'id' => $card_id])->find();
        $check_status = $card_list['check_status'];
        $status = $card_list['status'];
        $curr_balance = $card_list['balance'];
        $bank_type      = $card_list['bank_type'];
        $card_type      = $card_list['card_type'];

        if($bank_type == 3){
            $is_action_bank3 = getSetting('is_action_bank3');
            if($is_action_bank3 == 1){
                return $this->err('卡头正在维护中,请稍后操作.');
            }
        }
//        $card_num       = $card_list['card_num'];
//        if(substr($card_num,0,6) == 451946){
//            return $this->err('卡头451946正在维护中,请您选择其他卡头操作.');
//        }

        if ($check_status != 1) return $this->err('已开卡的类型才能进行此操作.');
        $redis_card_course = Cache::store('redis')->get('user_update_balance_' . $user_name);
        $msg_success = '更新成功.';
        $msg_error = '更新失败.';
        if (!$redis_card_course) {
            $model = new cardsModel();
            switch ($type) {
                case 'add_balance':
                    $cardSetList    = $this->getCardSet();
                    $rate           = $cardSetList[$bank_type][$card_type]['rate_fund'];
                    $server_amount  = $amount * $rate;
                    $total_amount   = $amount + $server_amount;
                    if ($status != 1) return $this->err('已激活状态才能进行此操作.');
                    if (!check_param($amount, 'zInt')) return $this->err('金额必须为正整数.');
                    if ($total_amount > $user_balance) return $this->err('账户余额不足.');
                    if ($amount - $user_balance > 0) return $this->err('账户余额不足.');
                    $re = $model->setCardBalance('add_card_balance',
                        $data + [
                            'user_id'   => $this->user_id,
                            'rate'      => $rate
                        ]);
                    break;
                case 'det_balance':
                    if ($status != 1) return $this->err('已激活状态才能进行此操作.');
                    if (!check_param($amount, 'zInt')) return $this->err('金额必须为正整数.');
                    if ($amount > $curr_balance) return $this->err('卡余额不足.');
                    //充值金额小于开卡金额，提示错误
                    if (($curr_balance - $amount) < $create_amount) {
                        return ['blog' => false, 'msg' => "卡余额减少后不能少于 $ {$create_amount}."];
                    }
                    $re = $model->setCardBalance('deduct_card_balance', $data + [
                            'user_id'   => $this->user_id
                        ]);
                    break;
                case 'del':
                    if ($status == '3') return $this->err('此卡已经删除.');
                    if($curr_balance < 0) return $this->err('卡余额为负值，请充值后再进行操作.');
                    $re = $model->setCardCancel($data + [
                            'user_id' => $this->user_id,
                            'bank_type' => $bank_type
                        ]);
                    $msg_success = '删除成功.';
                    $msg_error = '删除失败.';
                    break;
                case 'card_remark':
                    $re = $model->setCardRemarks($data + ['user_id' => $this->user_id]);
                    break;
                case 'address':
                    if (check_param($data['billing_address'] , 'zn')) return $this->err('街道地址不能有中文字符.');
                    if (check_param($data['city'] , 'zn')) return $this->err('城市不能有中文字符.');
                    if (check_param($data['state'] , 'zn')) return $this->err('州不能有中文字符.');
                    if (check_param($data['zip'] , 'zn')) return $this->err('邮编不能有中文字符.');
                    if (!is_numeric($data['zip'])) return $this->err('邮编必须为数字.');
                    $re = $model->changeCardAddress($data + ['user_id' => $this->user_id]);
                    break;
            }
        } else {
            return $this->err('服务器忙,请稍后再试.');
        }
        if ($re) {
            return $this->scs($msg_success);
        } else {
            return $this->err($msg_error);
        }

    }

    public function tranList()
    {
        $card_count = Db::name('cards')->where(['user_id'=>$this->user_id])->count();
        if($card_count <= 0){
            return $this->redirect(url('/index/cards/index'));
        }

        $users_list = Db::name('user')->where(['id' => $this->user_id])->find();
        $grade         =   $users_list['grade'];
        if($grade == 0){
            return $this->redirect(url('/index/user/cardCheck'));
        }

        if ($this->request->isAjax()) {
            $fcModel = new CardsTrans();
            return $fcModel->tableDataIndex(input('param.') + ['user_id' => $this->user_id]);
        }
        View::assign([
            'menu_child' => 'list_tran',
            'tran_type' => ['Authorized', 'Declined', 'Posted', 'Reversal', 'Credit']
        ]);
        return View::fetch();
    }

//    public function tranList123()
//    {
//        $card_count = Db::name('cards')->where(['user_id'=>40788])->count();
//        if($card_count <= 0){
//            return $this->redirect(url('/index/cards/index'));
//        }
//
//        if ($this->request->isAjax()) {
//            $fcModel = new CardsTrans();
//            return $fcModel->tableDataIndex123(input('param.') + ['user_id' => 40788]);
//        }
//        View::assign([
//            'menu_child' => 'list_tran',
//            'tran_type' => ['Authorized', 'Declined', 'Posted', 'Reversal', 'Credit']
//        ]);
//        return View::fetch();
//    }

    /**
     * 批量改变卡状态
     */
    public function changeCardStatus()
    {
        $data = input('param.');
        if (!$this->check_cardId_user($data['id_array'])) return $this->err('用户和卡的详细信息不匹配');

        $user_list = Db::name('user')->find($this->user_id);
        $status    = $user_list['status'];
        if($status == 2){
            return $this->err('账号已冻结,请联系管理员');
        }

        if (count($data['id_array']) == 1) {
            $card_id = $data['id_array'][0];
            $is_action = Db::name('cards')->where(['id' => $card_id])->value('is_action');
            if ($is_action == 1) return $this->err('卡片异常，请联系管理员.');
        }
        $num = cardsModel::changeCardStatus($data + ['user_id' => $this->user_id]);
        if ($num) {
            return $this->scs("{$num} 张卡更新成功.");
        } else {
            return $this->err('卡更新失败.');
        }
    }

    public function check_cardId_user($card_id)
    {
        if (is_array($card_id)) {
            $count_card = count($card_id);
            $card_id_join = implode(',', $card_id);
            $list = Db::name('cards')
                ->where("user_id={$this->user_id} 
                and id in ({$card_id_join})")
                ->count();
            if ($count_card == $list) {
                return true;
            } else {
                return false;
            }
        } else {
            $list = Db::name('cards')
                ->where([
                    'id' => $card_id,
                    'user_id' => $this->user_id
                ])->find();
        }
        if ($list) {
            return true;
        } else {
            return false;
        }
    }

    public function shopSearch()
    {
        $getDelKey = getSetting('tran_key_name');
        if($this->request->isAjax()){
            $fcModel = new ComCardsTrans();
            $param   = input('param.');
            $shopping = $param['shopping'] ?? '';
            $key_array = explode(',' , $getDelKey);
            $i = true;
            if(!empty($shopping)){
                foreach ($key_array as $k_ka=>$v_ka) {
                    //判断字符串中存在子字符串
                    if (strpos(strtolower($v_ka), strtolower($shopping)) !== false) {
                        $i=false;
                    }
                }
            }
            if($i){
                return $fcModel->getSearchShops($param + ['user_id' =>$this->user_id]);
            }else{
                return $result = [
                    'code'  => 0,
                    'msg'   => lang('get info success'),
                    'data'  => [],
                    'count' => 0,
                ];
            }
        }
        View::assign([
            'menu_child' => 'card_header',
            'menu_class' => 'card_header',
            'tran_key_name' => $getDelKey
        ]);
        View::layout(true);
        return View::fetch();
    }
}